/*
 * Copyright (C) 2007 BitLab.com.ua
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ua.com.bitlab.rsprocessor;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Yaroslav Yermak
 * @version 1.0, Mar 7, 2007
 */
public class ListProcessor<T> {
// ------------------------------ FIELDS ------------------------------

    private Chain chain;
    private String primaryKey;

// --------------------------- CONSTRUCTORS ---------------------------

    public ListProcessor(String primaryKey, RsProcessor processor) {
        this.primaryKey = primaryKey;
        this.chain = new Chain();
        chain.addProcessor(primaryKey, processor);
    }

// -------------------------- OTHER METHODS --------------------------

    public void addHandler(String key, RsProcessor rsProcessor) {
        chain.addProcessor(key, rsProcessor);
    }

    public List<T> handle(ResultSet rs) throws SQLException {
        ResultSetWrapper resultSetWrapper = new ResultSetWrapper(rs);
        List<T> rows = new ArrayList<T>();
        while (resultSetWrapper.next()) {
            T result = this.handleRow(resultSetWrapper);
            if (result != null && !rows.contains(result)) {
                rows.add(result);
            }
        }
        return rows;
    }

    private T handleRow(ResultSet rs) throws SQLException {
        chain.reset();
        return (T) chain.handleBean(rs, primaryKey);
    }
}
